package cn.cl.gulimall.product.service.impl;

import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.cl.common.utils.PageUtils;
import cn.cl.common.utils.Query;

import cn.cl.gulimall.product.dao.ProductAttrValueDao;
import cn.cl.gulimall.product.entity.ProductAttrValueEntity;
import cn.cl.gulimall.product.service.ProductAttrValueService;
import org.springframework.transaction.annotation.Transactional;


@Service("productAttrValueService")
public class ProductAttrValueServiceImpl extends ServiceImpl<ProductAttrValueDao, ProductAttrValueEntity> implements ProductAttrValueService {

	@Override
	public PageUtils queryPage(Map<String, Object> params) {
		IPage<ProductAttrValueEntity> page = this.page(
				new Query<ProductAttrValueEntity>().getPage(params),
				new QueryWrapper<ProductAttrValueEntity>()
		);

		return new PageUtils(page);
	}

	/**
	 * 4、保存spu的规格参数 pms_product_attr_value
	 */
	@Override
	public void saveProductAttr(List<ProductAttrValueEntity> productAttrValueEntities) {
		if (productAttrValueEntities != null || productAttrValueEntities.size() > 0) {
			this.saveBatch(productAttrValueEntities);
		}
	}

	/**
	 * SPU查询回显
	 */
	@Override
	public List<ProductAttrValueEntity> baseAttrlistforspu(Long spuId) {
		List<ProductAttrValueEntity> productAttrValueEntities = this.baseMapper.selectList(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id", spuId));
		return productAttrValueEntities;
	}

	/**
	 * SPU信息修改
	 */
	@Transactional
	@Override
	public void updateSpuAttr(Long spuId, List<ProductAttrValueEntity> productAttrValueEntities) {
		// 1、删除这个spuId之前对应的所有属性
		this.baseMapper.delete(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id", spuId));
		// 2、插入新的数据
		List<ProductAttrValueEntity> productAttrValueEntityList = productAttrValueEntities.stream().map((item) -> {
			item.setSpuId(spuId);
			return item;
		}).collect(Collectors.toList());
		this.saveBatch(productAttrValueEntityList);
	}
}